package com.five.taotao.order_details;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.five.taotao.Adapter.ProductOrderAdapter;
import com.five.taotao.Adapter.ShopcarAdapter;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.entity.DataResult;
import com.five.taotao.entity.OrderAdd;
import com.five.taotao.entity.OrderAddMulti;
import com.five.taotao.entity.Product;
import com.five.taotao.entity.ShoppingCart;
import com.five.taotao.selfwidget.Keyboard;
import com.five.taotao.selfwidget.MyListView;
import com.five.taotao.selfwidget.PayEditText;
import com.five.taotao.setup.HttpActivity;
import com.five.taotao.util.Constants;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class OrderConfirmActivity extends AppCompatActivity {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.shopcar_top)
    RelativeLayout shopcarTop;
    @BindView(R.id.tv_shopcar_line1)
    TextView tvShopcarLine1;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.tel)
    TextView tel;
    @BindView(R.id.lin)
    LinearLayout lin;
    @BindView(R.id.weChat)
    RadioButton weChat;
    @BindView(R.id.union)
    RadioButton union;
    @BindView(R.id.friend)
    RadioButton friend;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.hidden)
    TextView hidden;
    @BindView(R.id.mylv)
    MyListView mylv;
    @BindView(R.id.http)
    TextView http;
    @BindView(R.id.tmp)
    TextView tmp;
    @BindView(R.id.money_pay)
    TextView moneyPay;
    @BindView(R.id.pay_btn)
    TextView payBtn;
    @BindView(R.id.bottom)
    RelativeLayout bottom;

    @OnClick(R.id.back)
    public void back() {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        LayoutInflater inflater =LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.alert, null, false);
        dialog.setView(v);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        dialog.show();

    }

    private int flag = 1;
    private static final String[] KEY = new String[]{
            "1", "2", "3",
            "4", "5", "6",
            "7", "8", "9",
            "<<", "0", "完成"
    };

    private PayEditText payEditText;
    private Keyboard keyboard;

    private ShoppingCart.ListBean product1;
    private List<ShoppingCart.ListBean> mData;
    private ProductOrderAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirm);
        ButterKnife.bind(this);
        product1 = (ShoppingCart.ListBean) getIntent().getSerializableExtra("shopcar");

        Bundle bundle = getIntent().getExtras();
        mData = (List<ShoppingCart.ListBean>) bundle.get("list");

        if (mData == null) {
            mData = new ArrayList<>();
            if (product1 != null) {
                mData.add(product1);
                adapter = new ProductOrderAdapter(mData, this);
                mylv.setAdapter(adapter);
                moneyPay.setText((double)product1.getNum()*product1.getVipprice()+"");
            }
        } else {
            adapter = new ProductOrderAdapter(mData, this);
            mylv.setAdapter(adapter);
            double total = 0;
            for (int i = 0; i < mData.size(); i++) {
                total = total + mData.get(i).getVipprice()*mData.get(i).getNum();
            }
            moneyPay.setText(total+"");
        }



    }


    @OnClick({R.id.http, R.id.hidden, R.id.pay_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.http:
                final Intent intent = new Intent(this, HttpActivity.class);
                startActivity(intent);
                break;
            case R.id.hidden:
                weChat.setVisibility(View.VISIBLE);
                friend.setVisibility(View.VISIBLE);
                union.setVisibility(View.VISIBLE);
                text.setVisibility(View.VISIBLE);
                hidden.setVisibility(View.GONE);
                break;
            case R.id.pay_btn:
                OrderPopwindow();
                break;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);


    }

    /**
     * 订单的popwindow
     */
    private void OrderPopwindow() {
        View view1 = LayoutInflater.from(this).inflate(R.layout.pay_pop, null, false);
        final PopupWindow popupWindow = new PopupWindow(view1
                , ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view1.findViewById(R.id.img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(OrderConfirmActivity.this, HttpActivity.class);
                startActivity(intent1);
            }
        });
        //6.0以下点击popupWindow外边空白，popupWindow消失的操作
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        ColorDrawable colorDrawable = new ColorDrawable(0);
        popupWindow.setBackgroundDrawable(colorDrawable);

        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        popupWindow.setBackgroundDrawable(dw);
        backgroundAlpha(this, 0.5f);//0.0-1.0
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(OrderConfirmActivity.this, 1f);
            }
        });

        //设置动画效果
        popupWindow.setAnimationStyle(R.style.pop_anim);
        popupWindow.showAtLocation(view1, Gravity.BOTTOM, 0, 0);

        view1.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent intent1 = new Intent(OrderConfirmActivity.this, OrderDetailActivity.class);
                startActivity(intent1);*/
                popupWindow.dismiss();//关闭支付详情的pop
            }
        });
        view1.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();//关闭支付详情的pop
                payPopwindow();
            }
        });
    }

    /**
     * 支付的popwindow
     */
    private void payPopwindow() {
        View view1 = LayoutInflater.from(OrderConfirmActivity.this).inflate(R.layout.surepay, null, false);
        payEditText = (PayEditText) view1.findViewById(R.id.PayEditText_pay);
        keyboard = (Keyboard) view1.findViewById(R.id.KeyboardView_pay);
        final PopupWindow popupWindow = new PopupWindow(view1
                , ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        setSubView();
        initEvent(popupWindow);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        popupWindow.setBackgroundDrawable(dw);
        backgroundAlpha(OrderConfirmActivity.this, 0.5f);//0.0-1.0
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(OrderConfirmActivity.this, 1f);
            }
        });
        //设置动画效果
        popupWindow.setAnimationStyle(R.style.pop_anim);
        popupWindow.showAtLocation(view1, Gravity.BOTTOM, 0, 0);
        view1.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();//关闭支付的pop
            }
        });
    }

    private void setSubView() {
        //设置键盘
        keyboard.setKeyboardKeys(KEY);
    }

    private void initEvent(final PopupWindow popupWindow) {
        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {
                if (position < 11 && position != 9) {
                    payEditText.add(value);
                } else if (position == 9) {
                    payEditText.remove();
                } else if (position == 11) {
                    //当点击完成的时候，也可以通过payEditText.getText()获取密码，此时不应该注册OnInputFinishedListener接口
                    pay();
                }
            }
        });

        /**
         * 当密码输入完成时的回调
         */
        payEditText.setOnInputFinishedListener(new PayEditText.OnInputFinishedListener() {
            @Override
            public void onInputFinished(String password) {
                pay();
            }
        });
    }

    /**
     * 提交订单
     */
    public void pay() {

        if (mData == null) {
            OkHttpUtils
                    .post()
                    .url(Constants.OA_URL)
                    .addParams("cid", "0")
                    .addParams("pid", product1.getProductId() + "")
                    .addParams("uid", MyApplication.userId)
                    .addParams("num", product1.getNum() + "")
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            MyApplication.toast.toastShow("支付失败");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            MyApplication.toast.toastShow("支付成功");
                            finish();
                        }
                    });
        } else {
            List<OrderAddMulti> list = new ArrayList<>();

            for (int i = 0; i < mData.size(); i++) {
                OrderAddMulti orderAddMulti = new OrderAddMulti(mData.get(i).getCarid(),
                        mData.get(i).getProductId(),mData.get(i).getNum());
                list.add(orderAddMulti);
            }

            DataResult<OrderAddMulti> dr = new DataResult<OrderAddMulti>(200, list, list.size());
            Gson gson = new Gson();
            String drJS = gson.toJson(dr);

            OkHttpUtils
                    .post()
                    .url(Constants.OML_URL)
                    .addParams("orderAddMulti", drJS)
                    .addParams("uid", MyApplication.userId)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            MyApplication.toast.toastShow("支付失败");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            MyApplication.toast.toastShow("支付成功");
                            finish();
                        }
                    });
        }



    }

}
